using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BulletScript : MonoBehaviour
{
    [Header("子弹设置")]
    public float speed = 10f;
    public int damage = 1;
    public float lifeTime = 3f;
    public bool homing = true; // 是否追踪目标
    public float homingStrength = 5f; // 追踪强度
    
    private Transform target;
    private Rigidbody2D rb;
    // private float timer;
    private Vector2 direction;
    public Transform playerTransform; // 玩家引用，用于碰撞忽略
    
    // 在Bullet脚本中添加
    public GameObject hitEffect;
    public TrailRenderer trail;
    
    private Camera mainCamera;

    void Awake()
    {
        rb = GetComponent<Rigidbody2D>();
        if (rb != null)
        {
            rb.gravityScale = 0; // 确保无重力
            rb.bodyType = RigidbodyType2D.Dynamic; // 确保为动态刚体
        }
        else
        {
            Debug.LogError("子弹预制体缺少Rigidbody2D组件！", this);
        }
    }

    void Start()
    {
        // timer = 0f;
        //获取屏幕大小
        mainCamera = Camera.main;
    }

    public void SetTarget(Vector3 enemyTarget)
    {
        rb = GetComponent<Rigidbody2D>();
        
        // 确保目标点和子弹在同一个z平面上
        Vector3 targetPos = new Vector3(enemyTarget.x, enemyTarget.y, transform.position.z);
        Vector3 startPos = transform.position;
        
        // 计算朝向目标的方向向量
        direction = (targetPos - startPos).normalized;
        
        // 设置子弹朝向和速度
        SetDirection(direction);
    }
    
    public void SetDirection(Vector2 dir)
    {
        rb = GetComponent<Rigidbody2D>();
        direction = dir.normalized;
        
        // 重置计时器
        // timer = 0f;
        
        // 设置子弹朝向(让子弹头指向移动方向)
        transform.right = direction;
        
        // 验证速度和方向
        if (speed <= 0)
        {
            Debug.LogError("子弹速度必须大于0！当前值: " + speed, this);
            speed = 10f; // 设置默认速度
        }
        
        if (direction.sqrMagnitude < 0.01f)
        {
            Debug.LogWarning("子弹方向无效，使用默认方向", this);
            direction = Vector2.right; // 默认向右
        }
        
        // 设置初始速度
        rb.velocity = direction * speed;
        
        // 重置并启用拖尾效果
        if (trail != null)
        {
            trail.Clear();
            trail.enabled = true;
        }
        
        // 设置速度后启用碰撞体
        Collider2D collider = GetComponent<Collider2D>();
        if (collider != null)
            collider.enabled = true;
    }

    void Update()
    {
        //获取子弹当前位置是不是超过屏幕边缘，如果超过则销毁子弹
        // 将子弹的世界坐标转换为视口坐标(0-1范围)
        Vector3 viewportPosition = mainCamera.WorldToViewportPoint(transform.position);
        //判断子弹的位置是否超过屏幕边缘
        if (viewportPosition.x < 0 || viewportPosition.x > 1 || 
            viewportPosition.y < 0 || viewportPosition.y > 1)
        {
            BulletPool.GetInstance().ReturnBullet(gameObject);
            return;
        }
        // timer += Time.deltaTime;
        // if (timer >= lifeTime)
        // {
        //     BulletPool.GetInstance().ReturnBullet(gameObject);
        //     return;
        // }
        
        // 持续更新子弹朝向(确保旋转与移动方向一致)
        if (rb.velocity != Vector2.zero)
        {
            transform.up = rb.velocity.normalized;
        }

        // 追踪逻辑
        // if (homing && target != null)
        // {
        //     Vector2 direction = (target.position - transform.position).normalized;
        //     rb.velocity = Vector2.Lerp(rb.velocity, direction * speed, homingStrength * Time.deltaTime);
        //     transform.right = rb.velocity.normalized; // 更新子弹朝向
        // }
    }

    void OnDisable()
    {
        // 禁用时关闭碰撞体防止残留碰撞
        Collider2D collider = GetComponent<Collider2D>();
        if (collider != null)
            collider.enabled = false;

        // 重置物理状态
        if (rb != null)
        {
            rb.velocity = Vector2.zero;
            rb.angularVelocity = 0f;
        }
        // timer = 0f;
    }

    void OnTriggerEnter2D(Collider2D other)
    {
        // 忽略玩家和自身碰撞
        // 直接比较玩家Transform和子对象，不依赖标签
        if (other.transform == playerTransform || (playerTransform != null && other.transform.IsChildOf(playerTransform)))
            return;

        if (other.CompareTag("Enemy"))
        {
            if (hitEffect != null)
            {
                Instantiate(hitEffect, transform.position, Quaternion.identity);
            }
            EnemyController enemy = other.GetComponent<EnemyController>();
            if (enemy != null)
            {
                enemy.TakeDamage(damage);
            }
            BulletPool.GetInstance().ReturnBullet(gameObject);
        }
        else if (other.CompareTag("Wall"))
        {
            BulletPool.GetInstance().ReturnBullet(gameObject);
        }
    }
}
